// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace SnapObjects.Commons
{
    public class XmlConvertor
    {
        public static object Deserialize(string value, Type type)
        {
            object result;
            var xml = new XmlSerializer(type);
            using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(value)))
            {
                result = xml.Deserialize(stream);
            }
            return result;
        }

        public static T Deserialize<T>(string value)
        {
            var result = default(T);

            var xml = new XmlSerializer(typeof(T));
            using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(value)))
            {
                result = (T)xml.Deserialize(stream);
            }

            return result;
        }

        public static T DeserializeFromFile<T>(string xmlPath)
        {
            var xmlText = File.ReadAllText(xmlPath, Encoding.Unicode);

            return Deserialize<T>(xmlText);
        }

        public static string Serialize<T>(T value)
        {
            var result = new StringBuilder();

            var xml = new XmlSerializer(value.GetType());

            using (var writer = XmlWriter.Create(result))
            {
                xml.Serialize(writer, value);

                writer.Flush();
            }

            return result.ToString();
        }

        public static void SerializeToFile<T>(T value, string path)
        {
            var xml = Serialize(value);

            File.WriteAllText(path, xml, Encoding.Unicode);
        }
    }
}
